<?php
namespace jy_weishop_en\order;
defined('BY_JYA') or exit('error');
/*
	配送费
*/
class dispatch extends \plugin{
	public function get_freight($goods_list,$pcd='',$throw_error=false,$showbaoyou=false,$template_id=0){
		if(!$goods_list){
			if($showbaoyou){
				return array();
			}else{
				return 0;
			}
		}
		$this->throw_error=$throw_error;
		$total_price=0;
		$goods_total_price=0;
		$baoyoufee=0;
		$saleset=$this->plugin_setting('saleset');
		$newlist=array();
		foreach($goods_list as $goods){
			$goods_total_price+=$goods['total']*$goods['price'];
			if($template_id){
				$newlist[$template_id][]=$goods;
				continue;
			}
			$default_template_id=pdo_getcolumn('jy_weishop_dispatch',array('uniacid'=>$_SESSION['uniacid'],'isdefault'=>1),'id');
			$dispatch=pdo_get('jy_weishop_goods_dispatch',array('goodsid'=>$goods['goodsid']));
			if($dispatch['fullnoareas']){
				$dispatch['fullnoareas']=json_decode($dispatch['fullnoareas'],true);
			}
			if(!$dispatch['fullnoareas'] || !$this->check_pcd($pcd,$dispatch['fullnoareas'])){
					$dispatch['fullnum']=intval($dispatch['fullnum']);
					if($dispatch['fullnum'] && $goods['total']>=$dispatch['fullnum']){
						//单品满件包邮
						$isbaoyou=true;
						continue;
					}
					if($dispatch['fullmoney'] && $goods['total']*$goods['price']>=$dispatch['fullmoney']){
						//单品满额包邮
						$isbaoyou=true;
						continue;
					}
			}
			if($dispatch['type']==1){
				//统一运费
				$total_price+=$dispatch['price']*$goods['total'];
			}elseif($dispatch['template_id']){
				$newlist[$dispatch['template_id']][]=$goods;
			}else{
				$newlist[$default_template_id][]=$goods;
			}
		}
		if($newlist){			
			foreach($newlist as $template_id=>$item){
				$total_weight=0;
				$total_num=0;
				foreach($item as $gv){
					//$goods['price']=pdo_getcolumn('jy_weishop_goods',array('id'=>$goods['goodsid']),'price');
					$total_num+=$gv['total'];
					$total_weight+=$gv['total']*$gv['weight'];
				}
				if($total_num || $total_weight){
					$get_dispatch_price=$this->get_dispatch_price($pcd,$template_id,$total_weight,$total_num);				
					$total_price+=$get_dispatch_price['fee'];
					$outarea=$get_dispatch_price['outarea'];
				}
			}
		}
		$baoyou_man=$saleset['baoyou_status'] && $saleset['baoyou_man']>0?$saleset['baoyou_man']:0;
		//会员独立包邮
		if($saleset['baoyou_levelstatus'] && $saleset['baoyou_levelset']){
			$levelid = pdo_getcolumn('jy_weishop_member',array('uniacid'=>$_SESSION['uniacid'],'mid'=>$_SESSION['uid']),'level');
			$levelid=$levelid?:0;
			foreach($saleset['baoyou_levelset'] as $sv){
				if($sv['level_id']==$levelid){
					$baoyou_man=$sv['manfee'];
					$islevelman=$goods_total_price>=$sv['manfee']?1:0;
					break;
				}
			}
		}
		if($saleset['baoyou_status']){
			if($goods_total_price>=$saleset['baoyou_man'] || $islevelman){
				//满额包邮！
				if($showbaoyou){
					return array('is_peisong'=>0,'fee'=>0,'outarea'=>$outarea,'addbaoyoufee'=>$total_price,'isonebaoyou'=>$isbaoyou,'baoyou_man'=>$baoyou_man);
				}else{
					return 0;
				}
			}
		}
		if($showbaoyou){
			return array('is_peisong'=>0,'fee'=>$total_price,'outarea'=>$outarea,'addbaoyoufee'=>0,'isonebaoyou'=>$isbaoyou,'baoyou_man'=>$baoyou_man);
		}else{
			return $total_price;
		}
	}
	public function get_dispatch_price($pcd='',$template_id,$weight,$total){
		$dispatch=pdo_get('jy_weishop_dispatch',array('id'=>$template_id));
		if($dispatch['isdispatcharea']==0 && $pcd){
			//不配送区域
			$nodispatchareas=json_decode($dispatch['nodispatchareas'],true);
			if($this->check_pcd($pcd,$nodispatchareas)){
				$outarea=1;
				//if($this->throw_error){
				//	throw new \Exception('您的收货地址不在商品配送范围！');
				//}
				//exi('您的收货地址不在商品配送范围！','error');
			}
		}
		if($dispatch['isdispatcharea']==1 && $pcd){
			//只配送区域
			$onlydispatchareas=json_decode($dispatch['onlydispatchareas'],true);
			if(!$this->check_pcd($pcd,$onlydispatchareas)){
				$outarea=1;
				//if($this->throw_error){
				//	throw new \Exception('您的收货地址不在商品配送范围！');
				//}
				//exi('您的收货地址不在商品配送范围！','error');
			}
		}
		if($dispatch['type']==0){
			//按重量计费
			$count=$weight;
		}else{
			$count=$total;
		}
		$price=0;
		if($dispatch['isdispatcharea']<=1 || !$pcd){
			//统一计费
			if($dispatch['feetype']){
				$feeset=json_decode($dispatch['feeset'],true);
				paixu($feeset,'man','desc');
				foreach($feeset as $fv){
					if($count<=$fv['man']){
						$dispatch['shouweight']=$fv['shou'];
						$dispatch['shouprice']=$fv['shouprice'];
						$dispatch['xuweight']=$fv['xu'];
						$dispatch['xuprice']=$fv['xuprice'];
					}else{
						break;
					}
				}
			}
			$price=$dispatch['shouprice'];
			if($dispatch['xuweight'] && $dispatch['xuprice'] && $count>$dispatch['shouweight']){
				$price+=ceil(($count-$dispatch['shouweight'])/$dispatch['xuweight'])*$dispatch['xuprice'];
			}
			$DATA=ijson_encode($dispatch);
		}else{			
			//自定义配送区域，寻找匹配的配送区域设置
			$areas=json_decode($dispatch['areas'],true);
			if($areas){
				foreach($areas as $av){
					if($av['type']==0){
						$count=$weight;
					}else{
						$count=$total;
					}
					$av['area']=$av['area']?json_decode($av['area'],true):array();
					if($this->check_pcd($pcd,$av['area'])){
						//区域命中
						if($av['feetype']){
							$feeset=$av['feeset'];
							paixu($feeset,'man','desc');
							foreach($feeset as $fv){
								if($count<=$fv['man']){
									$av['shou']=$fv['shou'];
									$av['shouprice']=$fv['shouprice'];
									$av['xu']=$fv['xu'];
									$av['xuprice']=$fv['xuprice'];
								}else{
									break;
								}
							}
						}
						$isarea=true;
						$price=$av['shouprice'];
						if($av['xu'] && $av['xuprice'] && $count>$av['shou']){
							$price+=ceil(($count-$av['shou'])/$av['xu'])*$av['xuprice'];
						}
						break;
					}
				}
				$outarea=$isarea?0:1;
			}
		}
		return array('fee'=>$price,'outarea'=>$outarea);
	}
	public function get_peisong($address='',$storeid=0,$addressid=0,$order_total_price=0,$merchid=0){
		$city_express=$this->plugin_setting('citypeisong');
		if(!$city_express['pcd']['city']){
			exi('同城配送的所在城市没有设置！请联系管理员','error');
		}
		$city_express['iscity']=true;
		if($storeid){
					$storeinfo=pdo_get('jy_weishop_store',array('id'=>$storeid),array('lat_lng','pcd'));
					$storeinfo['lat_lng']=$storeinfo['lat_lng']?json_decode($storeinfo['lat_lng'],true):array();
					$storeinfo['pcd']=$storeinfo['pcd']?json_decode($storeinfo['pcd'],true):array();
					$city_express['lat_lng']=$storeinfo['lat_lng']?:$city_express['lat_lng'];
					$city_express['pcd']=$storeinfo['pcd']?:$city_express['pcd'];
		}
		//如果是商户
		if($merchid){
					$merchinfo=pdo_get('jy_merch_user',array('id'=>$merchid),array('lat_lng','pcd'));
					$merchinfo['lat_lng']=$merchinfo['lat_lng']?json_decode($merchinfo['lat_lng'],true):array();
					$merchinfo['pcd']=$merchinfo['pcd']?json_decode($merchinfo['pcd'],true):array();
					$city_express['lat_lng']=$merchinfo['lat_lng']?:$city_express['lat_lng'];
					$city_express['pcd']=$merchinfo['pcd']?:$city_express['pcd'];
		}
		//有地址情况下
		if($addressid){
			$addressinfo=pdo_get('core_address', array('id' => $addressid, 'uniacid' => $_SESSION['uniacid']));
			$addressinfo['pcd']=$addressinfo['pcd']?json_decode($addressinfo['pcd'],true):array();
			if(!$addressinfo['pcd']['city']){
				//exi('收货地址的城市不弄为空！请完善！','error');
			}
			if($addressinfo['pcd']['city']!=$city_express['pcd']['city']){
				$city_express['iscity']=false;
			}
			$addressinfo['lat_lng']=$addressinfo['lat_lng']?json_decode($addressinfo['lat_lng'],true):array();
			//坐标已经存在的话，直接计算距离！
			if($addressinfo['lat_lng']['lng'] && $addressinfo['lat_lng']['lat']){
				$city_express_data = $this->get_peisong_fee($city_express, $addressinfo['lat_lng']['lng'], $addressinfo['lat_lng']['lat'],$order_total_price,$merchid);
				return $city_express_data;
			}
			//如果没传地址，传了地址ID
			$address_srt=$addressinfo['pcd']['province'] . $addressinfo['pcd']['city'] . $addressinfo['pcd']['district'] . $addressinfo['pcd']['street'] . $addressinfo['address'];
			$address=$address?:$address_srt;
		}
		$city_express_data = array('state' => 0, 'enabled' => 0, 'fee' => 0, 'is_dispatch' => $city_express['is_dispatch']);
		if ($city_express_data['enabled']!=1) {
			$city_express_data['enabled'] = 1;
			$city_express_data['is_sum'] = $city_express['is_sum'];
			//有解析具体的地址,没坐标情况下，传过来解析出坐标
			if (!empty($address)) {
				$data = cfc('tools')->getgeocode($address, $city_express['geo_key']);
				if ($data['status'] == 1 && 0 < $data['count']) {
					$location = explode(',', $data['geocodes'][0]['location']);
					if($city_express['pcd']['city']!=$data['geocodes'][0]['city']){
						$city_express['iscity']=false;
					}
					if($addressid){
						$update=array(
							'lat_lng'=>ijson_encode(array('lat'=>$location[1],'lng'=>$location[0])),
							'area_code'=>$data['geocodes'][0]['citycode'],
						);
						pdo_update('core_address', $update, array('id' => $addressid, 'uniacid' => $_SESSION['uniacid']));
					}
					$city_express_data = $this->get_peisong_fee($city_express, $location[0], $location[1],$order_total_price,$merchid);
				}else{
					//解析地址，获取坐标失败
					$city_express['nolat_lng']=1;
					$city_express_data = $this->get_peisong_fee($city_express, '', '',$order_total_price,$merchid);
				}
			}else{
				//没收货地址情况
				$city_express_data = $this->get_peisong_fee($city_express, '', '',$order_total_price,$merchid);
			}
		}
		
		return $city_express_data;
	}
	public function get_peisong_fee($city_express, $lng, $lat,$order_total_price=0,$merchid=0){
		$city_express_data = array('state' => 0, 'enabled' => 1, 'fee' => 0, 'is_sum' => $city_express['is_sum'], 'is_dispatch' => 0);
		if($city_express['lat_lng'] && $lng && $lat){
			$distance = cfc('tools')->getdistance($city_express['lat_lng']['lat'], $city_express['lat_lng']['lng'], $lat, $lng);
		}else{
			$distance = 0;
		}
		$city_express_data['juli']=$distance>0?$distance/1000:0;
		//满多少包邮？
		$city_express_data['baoyou_man']=$city_express['man_fee'];
		if ($city_express['iscity'] || intval($city_express['out_juli'])>$city_express_data['juli']) {
			$city_express_data['state'] = 1;
			if ($distance <= $city_express['start_km'] * 1000) {
				$city_express_data['fee'] = round($city_express['start_fee'], 2);
			}elseif ($city_express['start_km'] * 1000 < $distance && $distance <= $city_express['start_km'] * 1000 + $city_express['pre_km'] * 1000) {
				$km = $distance - intval($city_express['start_km'] * 1000);
				$city_express_data['fee'] = round($city_express['start_fee'] + $city_express['pre_km_fee'] * ceil($km / 1000), 2);
			}else {
				$city_express_data['fee'] = $city_express['fixed_fee']?round($city_express['fixed_fee'], 2):round($city_express['start_fee']*3, 2);
			}
			if($city_express['man_fee']>0 && $order_total_price>=$city_express['man_fee']){
				//满额免配送！
				$city_express_data['addbaoyoufee']=$city_express_data['fee'];
				$city_express_data['fee']=0;
			}
			if($city_express['out_price']>0 && $order_total_price<$city_express['out_price']){
				//多少钱起送
				$city_express_data['no_out_price']=$city_express['out_price'];
			}
			$city_express_data['iscity']=1;
			if($city_express['out_juli']>0 && intval($city_express['out_juli'])<$city_express_data['juli']){
				$city_express_data['maxout_juli']=intval($city_express['out_juli']);
				$city_express_data['outarea']=1;
			}
		}elseif($city_express['out_juli']>0 && intval($city_express['out_juli'])<$city_express_data['juli']){//超出最大距离
			$city_express_data['maxout_juli']=intval($city_express['out_juli']);
			$city_express_data['outarea']=1;
		}elseif($city_express['nolat_lng']){//没有解析到地址，就用起始运费
			$city_express_data['nolat_lng']=1;
			$city_express_data['iscity']=0;
			$city_express_data['fee'] = round($city_express['start_fee']*1, 2);
		}else{//超出同城,不使用快递方式,不配送
			$city_express_data['outarea']=1;
			$city_express_data['iscity']=0;
		}
		if($city_express_data['outarea'] && $city_express['is_dispatch']==1){//超出同城,使用快递方式
			$city_express_data['is_dispatch']=1;
		}
		//如果是商户：
		if($merchid){
			if($this->plugin_exists('jy_merch')){
				$merch=pdo_get('jy_merch_user',array('id'=>$merchid,'uniacid'=>$_SESSION['uniacid']));
				if($merch['mypeisong']){
					$city_express_data['fee']=$merch['out_pay'];
					if($city_express_data['no_out_price']>0){
						$city_express_data['no_out_price']=$merch['out_price']?:$city_express_data['no_out_price'];
					}
					$city_express_data['baoyou_man']=$merch['man_fee'];
					if($merch['out_pay']>0 && $merch['man_fee']>0 && $order_total_price>=$merch['man_fee']){
						//满额免配送！
						$city_express_data['addbaoyoufee']=$merch['out_pay'];
						$city_express_data['fee']=0;
					}
					$ismypeisong=1;
				}				
				if($merch['out_juli']>0 && $city_express_data['juli']<$merch['out_juli']){
					$city_express_data['iscity']=1;
					$city_express_data['maxout_juli']=$merch['out_juli'];
					$city_express_data['outarea']=0;
				}
				if($merch['out_juli']>0 && $city_express_data['juli']>$merch['out_juli']){
					$city_express_data['maxout_juli']=$merch['out_juli'];
					$city_express_data['outarea']=1;
				}
				if($city_express_data['outarea']){//超出同城,使用快递方式
					if($city_express['is_dispatch']==1 && !$merch['opensendtype']){
						$city_express_data['is_dispatch']=1;
					}elseif(strpos($merch['opensendtype'],'4') !== false){
						$city_express_data['is_dispatch']=1;
					}else{
						$city_express_data['is_dispatch']=0;
					}
				}
			}
		}
		//深夜服务费：
		if($city_express['lateye_fee']>0){
			$days=date('Y-m-d',TIMESTAMP);
			$start=strtotime($days.' '.$city_express['lateye_time']['start']);
			$end=strtotime($days.' '.$city_express['lateye_time']['end']);
			if($start>$end){
					//0点前
					if(TIMESTAMP>$start && TIMESTAMP>$end){
						$end=$end+24*3600;
					}
					//0点后
					if(TIMESTAMP<$start && TIMESTAMP<$end){
						$start=$start-24*3600;
					}
			}
			if(TIMESTAMP>$start && TIMESTAMP<$end){
					$city_express_data['lateye_fee']=$city_express['lateye_fee'];
					$city_express_data['fee'] +=$city_express_data['lateye_fee'];
			}
		}
		//恶劣环境服务费
		if($city_express['on_teshufee']==1){
			$city_express_data['teshufee']=$city_express['teshufee'];
			$city_express_data['fee'] +=$city_express_data['teshufee'];
		}
		$data=ijson_encode($city_express_data);
		return $city_express_data;
	}
	public function get_address($addressid=0,$store_id=0,$sendtype=1){
			if($sendtype==4){
				$item['address']=pdo_get('jy_weishop_store',array('uniacid'=>$_SESSION['uniacid'],'id'=>$store_id),array('address','pcd'));
			}else{
				if(intval($addressid)){
					$item['address']=pdo_get('core_address',array('mid'=>$_SESSION['uid'],'id'=>intval($addressid)));
					$item['addressid']=intval($addressid);
				}else{
					$member_address=pdo_getall('core_address',array('isdel'=>0,'mid'=>$_SESSION['uid']));
					if($member_address){
						foreach($member_address as &$address){
							if($address['isdefault']){
								$item['addressid']=$address['id'];
								$item['address']=$address;
								break;
							}
						}
						if(!$item['addressid']){
							$item['addressid']=$member_address['0']['id'];
							$item['address']=$member_address['0'];
						}
						
					}
				}
			}
			return $item;
	}
	public function up_dispatch($order,$item,$addressid,$store_id=0,$merch=array(),$template_id=0){
			$get_address=$this->get_address($addressid,$store_id,$order['sendtype']);
			$item['address']=$get_address['address'];
			$item['addressid']=$get_address['addressid'];
			$city_express=$this->plugin_setting('citypeisong');
			if($item['address']){
				$item['address']['pcd']=json_decode($item['address']['pcd'],true);
				try{
					if($city_express['isopen']  || $_SESSION['is_dish']){
						$addressinfo=$item['address']['pcd']['province'] . $item['address']['pcd']['city'] . $item['address']['pcd']['district'] . $item['address']['pcd']['street'] . $item['address']['address'];
						$get_freight=$this->get_peisong($addressinfo,$store_id,$item['address']['id'],$order['total_price'],$merch['id']);
						if($get_freight['is_dispatch']==1){
							$get_freight=$this->get_freight($order['list'],$item['address']['pcd'],true,true);
						}else{
							$get_freight['is_peisong']=$order['is_peisong']=1;
							$order['peisong_juli']=price($get_freight['juli']);
							//不在同城,不能下单！
							$order['outarea']=$get_freight['outarea'];
							$order['maxout_juli']=$get_freight['maxout_juli'];
							if($get_freight['iscity']==0 || ($merch['out_juli']>0 && $get_freight['juli']>0 && $get_freight['juli']>$merch['out_juli'])){
								$order['outarea']=1;
								$order['maxout_juli']=$merch['out_juli']?:'';
							}
							$order['isnocity']=$get_freight['iscity']?0:1;
						}
					}else{
						$get_freight=$this->get_freight($order['list'],$item['address']['pcd'],true,true,$template_id);
						if($get_freight['outarea']){
								$order['outarea']=1;
						}
					}
					$order['dispatchprice']=$get_freight['fee'];
					$order['isonebaoyou']=$get_freight['isonebaoyou'];
					$order['addbaoyoufee']=$get_freight['addbaoyoufee'];
					$order['baoyou_man']=$get_freight['baoyou_man']?:0;
					$order['lateye_fee']=$get_freight['lateye_fee']?:0;
					$order['teshufee']=$get_freight['teshufee']?:0;
				}catch(Exception $e){
					unset($item['address'],$item['addressid']);
					$order['dispatchprice']=0;
					$item['isnoarea']=1;
				}
			}else{
				if($city_express['isopen'] || $_SESSION['is_dish']){
						$get_freight=$this->get_peisong('',$store_id,'',$order['total_price'],$merch['id']);
						if($get_freight['is_dispatch']==1){
							$get_freight=$this->get_freight($order['list'],'',true,true);
						}else{
							$get_freight['is_peisong']=$order['is_peisong']=1;
							$order['peisong_juli']=price($get_freight['juli']);
							$order['isnocity']=$get_freight['iscity']?0:1;
						}
				}else{
					$get_freight=$this->get_freight($order['list'],'',true,true,$template_id);
				}
				$order['dispatchprice']=$get_freight['fee'];
				$order['isonebaoyou']=$get_freight['isonebaoyou'];
				$order['addbaoyoufee']=$get_freight['addbaoyoufee'];
				$order['baoyou_man']=$get_freight['baoyou_man']?:0;
				$order['lateye_fee']=$get_freight['lateye_fee']?:0;
				$order['teshufee']=$get_freight['teshufee']?:0;
			}
			//多少钱起送
			$order['no_out_price']=$get_freight['no_out_price']?:0;
			$get_freight['juli']=price($get_freight['juli']);
			$order['is_peisong']=$get_freight['is_peisong'];
			return array('order'=>$order,'item'=>$item,'get_freight'=>$get_freight);
	}
	public function check_pcd($pcd='',$area){
		//检查行政区划是否存在于区域数组
		//如果没有传地址，就默认成功
		if(!$pcd){
			return true;
		}
		if(!$area[$pcd['province']]){
			return false;
		}
		if($area[$pcd['province']]===true){
			return true;
		}
		if(!$area[$pcd['province']][$pcd['city']]){
			return false;
		}
		if($area[$pcd['province']][$pcd['city']]===true){
			return true;
		}
		if(!$area[$pcd['province']][$pcd['city']][$pcd['district']]){
			return false;
		}
		return true;
	}
}